/*
 *   Licensed to the Apache Software Foundation (ASF) under one
 *   or more contributor license agreements.  See the NOTICE file
 *   distributed with this work for additional information
 *   regarding copyright ownership.  The ASF licenses this file
 *   to you under the Apache License, Version 2.0 (the
 *   "License"); you may not use this file except in compliance
 *   with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing,
 *   software distributed under the License is distributed on an
 *   "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 *   KIND, either express or implied.  See the License for the
 *   specific language governing permissions and limitations
 *   under the License.
 *
 */
package com.cloud.control.service.socket.codes;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.example.imagine.step1.ImageResponse;

import com.cloud.control.service.socket.entity.ProxyEntity;
import com.cloud.control.service.socket.entity.SenderEntity;
import com.cloud.control.service.socket.handler.ProxyProtocolHandler;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * an encoder for {@link ImageResponse} objects 
 * 这个应该是输出一个HfsEntity的内容给Client时的处理!
 * AbstractIoSession Line 494
 * 调用IOSession的write方法时,会触发此监听器!
 * @author <a href="http://mina.apache.org">Apache MINA Project</a>
 */
public class ProxyResponseEncoder extends ProtocolEncoderAdapter {
    private final static Log log = LogFactory.getLog(ProxyResponseEncoder.class);

    /*
     * 转换生成返回的TCP报文字符串！
     * ProxyProtocolHandler.java write直接写的string,所以这里也无需处理编码
     * ProxyEntity & SenderEntity
     */
    public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
    	String entity="";
    	try {
			entity = (String) message;
			int capacity =entity.length();//包长度计算
			
			IoBuffer buffer = IoBuffer.allocate(capacity, false);
      
			buffer.put(entity.getBytes());
			buffer.flip();
			//int buffLen=(entity.length()>50)?50:entity.length();
			log.info("TCP Server send a message:" +entity);
			out.write(buffer);
		} catch (Exception e) {
			log.error(e.getMessage());
		}

    }

}
